package com.xnx.bincker.leader.controller.admin.system;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xnx.bincker.leader.core.annotation.IgnoreProperties;
import com.xnx.bincker.leader.core.annotation.OnlyIncludeProperties;
import com.xnx.bincker.leader.core.domain.BasicEntity;
import com.xnx.bincker.leader.domain.Authority;
import com.xnx.bincker.leader.domain.Role;
import com.xnx.bincker.leader.service.RoleService;
import com.xnx.bincker.leader.core.annotation.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Example;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;

@RestController
@RequestMapping("admin/system/role")
public class RoleController {
	private final RoleService roleService;

	@Autowired
	public RoleController(
        RoleService roleService
        ) {
		this.roleService = roleService;
	}

	@GetMapping
	@Menu(id="31d2af65-a1bc-41bd-b912-6b68011d658a", name = "角色管理")
	@com.xnx.bincker.leader.core.annotation.Authority(id="e36e8d18-bdd4-435b-8afd-8ce16c0069cc", remark = "角色列表")
    @IgnoreProperties(target = Role.class, value = {"authorities"})
	public Page<Role> list(
            @Validated(BasicEntity.ValidGroup.Search.class) Role role,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size){
		PageRequest pageRequest = PageRequest.of(page, size);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnorePaths("id", "authority");
        Role example = new Role();
        example.copyProperties(BasicEntity.Search.class, role);
        return roleService.findAll(Example.of(example, matcher), pageRequest);
	}

	@GetMapping(value = "/{id}")
    @com.xnx.bincker.leader.core.annotation.Authority(id="83f33d4c-521e-49f4-b38d-010de03ab983", remark = "角色详情")
	public Role get(@PathVariable String id){
        return roleService.findById(id).orElse(new Role());
	}

	@PostMapping
    @OnlyIncludeProperties(target = Authority.class, value = {"id"})
    @com.xnx.bincker.leader.core.annotation.Authority(id="eed43724-ba7b-4f80-aa3b-58794f386366", remark = "新增角色")
	public Role add(@RequestBody @Validated(BasicEntity.ValidGroup.Insert.class) Role role) {
        return roleService.save((Role) role.cloneByAnnotation(BasicEntity.Insert.class));
    }

    @DeleteMapping("/{id}")
    @com.xnx.bincker.leader.core.annotation.Authority(id="19390dcb-7341-4d1c-bf82-c55dfafac695", remark = "删除角色")
    public void delete(@PathVariable String id) {
        roleService.deleteById(id);
    }
}
